import urllib,urllib2,re,xbmc,xbmcplugin,xbmcgui,os,sys,xmlrpc2scgi,time
from datetime import date

__version__     = '0.99'
__name__        = 'TorrentDisplay'

MyPath  = os.getcwd()
MyMedia = MyPath +'/media/'
#BURL    = 'http://www.mininova.org'

## Variable Set Refresh or No Refresh
DirRefresh = False

## Used to force correct positions of entries uploaded.
index_no = 0

rpc = xmlrpc2scgi.RTorrentXMLRPCClient("scgi://localhost:5000")

Tor = {}



def fetchDetail(hash, method):
        obj = eval("rpc.d."+method)
        result = None
        if not method.startswith("__") and callable(obj):
            try:
                result = obj(hash)
            except:
                pass

        return result

def UpdateSettings():
        print '--UpdateSettings--'
        global SORTORDER,FILTERSEEDS
        SORTORDER      =   ('name','added','size','seeds','leech')[int(xbmcplugin.getSetting("sortorder"))]
        FILTERSEEDS    =   xbmcplugin.getSetting("filterseeds")
        print 'Sort Order:'+ str(SORTORDER) +' -- Filter Seeds:'+ str(FILTERSEEDS)

        
def FILES(dir):
        print '--FILES--'
        ## fetch data from rtorrent
        ###################################    0             1            2                    3                     4                5                    6                        7                 8                 9                10                11                 12
        Tar = rpc.d.multicall("default", "d.get_hash=", "d.get_loaded_file=", "d.is_active=", "d.get_complete=", "d.get_bytes_done=", "d.get_size_bytes=", "d.get_down_rate=", "d.get_up_rate=", "d.get_up_total=", "d.get_ratio=", "d.get_tied_to_file=", "d.get_loaded_file=", "d.is_active=")

        #Tor = {}
        for _a in Tar :
                #print unicode(_a[10]) #.rsplit('/', 1)[1])
                Nm                  =   _a[0]
                Tor[Nm]             =   {}
                name = unicode(_a[10])
                Tor[Nm]['Name']     =   name.rsplit('/', 1)[1]
                Tor[Nm]['Url']      =   str(_a[1])
                Tor[Nm]['Size']     =   str((int(_a[5])/1024))
                Tor[Nm]['DownRate']   = str((int(_a[6])/1024))
                Tor[Nm]['UpRate']   = str((int(_a[7])/1024))
                Tor[Nm]['Perc']     = str((int(_a[4])*100)/int(_a[5]))

                Image = None
                if _a[12] == 0:
                    Image  =   MyMedia +'pause.png'
                else:
                    Image  =   MyMedia +'start.png'

                Label1 = unicode(Tor[Nm]['Name']) + ' -Size '+ str(Tor[Nm]['Size']) +'-Complete '+ str(Tor[Nm]['Perc'] +'%')
#                if FILTERSEEDS == 'true' and int(TmpSeeds) != 0:
                addDir(Label1,unicode(dir),unicode(Nm),3, Image)
                #print u'-- added --' + unicode(Label1)


re_digits_nondigits = re.compile(r'\d+|\D+')

def _commafy(s):

    r = []
    for i, c in enumerate(reversed(s)):
        if i and (not (i % 3)):
            r.insert(0, ',')
        r.insert(0, c)
    return ''.join(r)

def FormatWithCommas(format, value):

    parts = re_digits_nondigits.findall(format % (value,))
    for i in xrange(len(parts)):
        s = parts[i]
        if s.isdigit():
            parts[i] = _commafy(s)
            break
    return ''.join(parts)


def getid(a):
    return a[3]

def OPTIONS(hash):
        print '--OPTIONS--'+hash

        dt = date.today()
        #self.strActionInfo.setLabel('Torrent: '+fetchDetail(hash,'get_name'))
        Det = [['' for i in range(4)] for j in range(18)]
        #display all the details associated with the selected torrent
        
        Image  =   MyMedia +'\\Health-2.png'
        addDir('Torrent Details','', hash, 3, Image)
        
        if fetchDetail(hash,  'is_active') == 0:
            #addDetail('Resume Torrent','', hash, 7, Image)
            addDir('Resume Torrent','', hash, 7, Image)
        else:
            #addDetail('Pause Torrent','', hash, 6, Image)
            addDir('Pause Torrent','', hash, 6, Image)
        
        #addDetail('Cancel Torrent','', hash, 5, Image)
        addDir('Cancel Torrent','', hash, 5, Image)

def DETAILS(hash):
        print '--DETAILS--'+hash

        dt = date.today()
        #self.strActionInfo.setLabel('Torrent: '+fetchDetail(hash,'get_name'))
        Det = [['' for i in range(4)] for j in range(18)]
        #display all the details associated with the selected torrent

        Det[0] = ['Ratio', '%0.2f ' % float(float(rpc.d.get_ratio(hash))/100), 1, 1]
        Det[1] = ['Size', FormatWithCommas('%d', rpc.d.get_size_bytes(hash) / 1024), 1, 2]
        Det[2] = ['Downloaded', FormatWithCommas('%d', rpc.d.get_bytes_done(hash) / 1024), 1, 3]
        Det[3] = ['Uploaded',  FormatWithCommas('%d', rpc.d.get_up_total(hash) / 1024), 1, 4]
        Det[4] = ['Chunk Size', FormatWithCommas('%d', fetchDetail(hash, 'get_chunk_size') / 1024), 1, 5]
        Det[5] = ['Message', fetchDetail(hash, 'get_message'), 1, 6]
        if fetchDetail(hash, 'get_complete') == 1:
            Det[6] = ['Complete', 'Completed', 1, 7]
        else:
            Det[6] = ['Complete', 'Incompleted', 1, 7]
        Det[7] = ['Completed Bytes', FormatWithCommas('%d', fetchDetail(hash, 'get_completed_bytes') / 1024), 1, 8]
        Det[8] = ['Completed Chunks', fetchDetail(hash, 'get_completed_chunks'), 1, 9]
        Det[9] = ['Current Connections', fetchDetail(hash, 'get_connection_current'), 1, 10]
        Det[10] = ['Leech Connections', fetchDetail(hash, 'get_connection_leech'), 1, 11]
        Det[11] = ['Connection Seed', fetchDetail(hash, 'get_connection_seed'), 1, 12]
        Det[12] = ['Creation Date', dt.fromtimestamp(fetchDetail(hash, 'get_creation_date')).strftime("%d/%m/%y"), 1, 13]
        Det[13] = ['Down Rate', FormatWithCommas('%d', fetchDetail(hash, 'get_down_rate') / 1024), 1, 14]
        Det[14] = ['Down Total', FormatWithCommas('%d', fetchDetail(hash, 'get_down_total') / 1024), 1, 15]
        Det[15] = ['Left Bytes', FormatWithCommas('%d', fetchDetail(hash, 'get_left_bytes') / 1024), 1, 16]
        if fetchDetail(hash, 'is_private') == 1:
            Det[16] = ['Tracker Type', 'Private', 1, 17]
        else:
            Det[16] = ['Tracker Type', 'Public', 1, 17]

        Det.sort(key=getid)
        n = 0
        for _d in Det :
                if _d[2] == 1:
                    Image  =   MyMedia +'\\Health-2.png'
                    #Label1 = str(str(_d[0]) + ' ' + str(_d[1])

                    addDetail(str(_d[0]).ljust(30)+' '+str(_d[1]).rjust(30),'', hash, None, Image)
                    #detail = xbmcgui.ListItem(str(_d[0]), str(_d[1]), Image, Image)
                    #self.detailInfo.addItem(xbmcgui.ListItem(str(_d[0]), str(_d[1]), Image, Image))
                    print '-- added --' + str(getid(_d)) +' '+ str(_d[0]) + ' ' + str(_d[1])

                
def NiceName(fName):
        NewName     =   ''
        tName       =   fName.rsplit('.',1)
        xName       =   tName[0][:30]
        if ( xName[0].isdigit() )   :
                xName = 'x'+ str(xName)
        for xChar in xName                  :
                if      xChar.isalnum()         :   NewName  += str(xChar)
                elif    xChar.isspace()         :   NewName  += '_'
                else                            :   pass
        if len(NewName) > 4                 :
                return NewName
        else                                :
                return None




def AddOne():
        global index_no
        index_no = index_no + 1
        return index_no


def displayInfo(hash):
        print 'displayInfo %s' % hash
        dialog = xbmcgui.Dialog()
        dialog.ok(hash)

def addDetail(name, label, hash, mode, iconimage):
        u=sys.argv[0]+"?hash="+hash+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&label="+urllib.quote_plus(label)
        ok=True
        liz=xbmcgui.ListItem(name, label, iconImage="DefaultFolder.png", thumbnailImage=iconimage)

        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False, totalItems=10)
        print '-- URL-- '+ hash
        return ok

def addDir(name,label, hash,mode,iconimage):
        u=sys.argv[0]+"?hash="+hash+"&mode="+str(mode)
        ok=True
        liz=xbmcgui.ListItem(name, label, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        d="XBMC.RunPlugin("+sys.argv[0]+"?hash="+hash+"&name="+name+"&mode=5)"
        PauseResume = None
        pr = None
        if fetchDetail(hash, 'is_active') == 1:
            PauseResume = 'Pause'
            pr="XBMC.RunPlugin("+sys.argv[0]+"?hash="+hash+"&mode=6)"
        else:
            PauseResume = 'Resume'
            pr="XBMC.RunPlugin("+sys.argv[0]+"?hash="+hash+"&mode=7)"
        try:
            liz.addContextMenuItems([("Delete", d),(PauseResume, pr)])
        except:
            print 'cannot add menu items'
            pass

        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        print '-- URL-- '+ u
        return ok



def pleaseWait():
        dlgWait = xbmcgui.DialogProgress()
        dlgWait.create("Please Wait")
        dlgWait.update(0)
        time.sleep(2)
        dlgWait.update(50)
        time.sleep(2)
        dlgWait.update(100)
        dlgWait.close()

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]

        return param

    
class Main:
    def __init__(self,  prog,  handle):
        UpdateSettings()
        self.params = get_params()
        self.url = None
        self.name = None
        self.mode = None
        self.label = None
        self.hash = None
        print '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& '+handle
        self.handle = handle
        self.prog = prog
        try:
            self.url = urllib.unquote_plus(self.params["url"])
        except:
            pass
        try:
            self.hash = str(self.params["hash"])
        except:
            pass
        try:
            self.name = urllib.unquote_plus(self.params["name"])
        except:
            pass
        try:
            self.mode = int(self.params["mode"])
        except:
            pass
        try:
            self.handle = int(self.params["handle"])
        except:
            pass
        try:
            self.name = urllib.unquote_plus(self.params["label"])
        except:
            pass

        print "Mode: " + str(self.mode)
        print "URL: " + str(self.url)
        print "Name: " + str(self.name)
        print "Label: " + str(self.label)
        print "Hash: " + str(self.hash)

        self.finished = False
        #return self.run()

    def run(self):

        result = False
        self.DirRefresh = False
        self.dialog = xbmcgui.Dialog()

        print '!!!!!!!!!!!!!!!!!!!!-- Files -- 0:' + sys.argv[0] + ' 1:' + sys.argv[1] + ' 2:' + sys.argv[2]

        if self.finished == False:

            if self.mode == None or self.hash == None or len(self.hash) < 1:
                print '-- Files --'
                FILES('.')

            if self.mode == 2: #display the 
                print '-- default options --'
                OPTIONS(self.hash)

            if self.mode == 3:
                print '-- default Details --'
                DETAILS(self.hash)


            if self.mode == 5: #delete
                if self.dialog.yesno('Deleting Torrent ' + self.name, 'Are you Sure?'):
                    fetchDetail(self.hash, 'erase')
                    print '-- wait --'
                    pleaseWait()
                    print '-- after wait --'
                    FILES('.')
                    self.DirRefresh = True
                    result = True
                    xbmc.executebuiltin("Container.Refresh")
                    #xbmc.executebuiltin("ReplaceWindow(Programs,%s)" % (self.prog))

            if self.mode == 6: #pause
                fetchDetail(self.hash, 'pause')
                print '-- wait --'
                pleaseWait()
                print '-- after wait --'
                FILES('.')
                self.DirRefresh = True
                result = True
                xbmc.executebuiltin("Container.Refresh")
                # returning back to the previous window
                #xbmc.executebuiltin("ReplaceWindow(Programs,%s)" % (self.prog))


            if self.mode == 7: #resume
                fetchDetail(self.hash, 'resume')
                pleaseWait()
                FILES('.')
                self.DirRefresh = True
                result = True
                xbmc.executebuiltin("Container.Refresh")
                #xbmc.executebuiltin("ReplaceWindow(Programs,%s)" % (self.prog))

            if result == False:
                xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE)
                print '--Dir refresh = '+ str(self.DirRefresh)+' ---- '+sys.argv[1]
                xbmcplugin.endOfDirectory(int(sys.argv[1]), updateListing=self.DirRefresh,  cacheToDisc=False)
            #return result
